package com.mengxiangnongfu.config.exception;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.mengxiangnongfu.constants.HttpStatus;
import com.mengxiangnongfu.vo.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常拦截
 *
 * @author Yang
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @Value("${spring.profiles.active}")
    private String active;

    /**
     * 拦截MethodArgumentNotValidException
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public AjaxResult jsonErrorHandler(Exception e) {
        //开发模式下打印异常详情
        if (active.equals("dev")) {
            e.printStackTrace();
        }
        //记录日志
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("\n触发类型:" + e.getClass() + "\n");
        stringBuffer.append("触发时间:" + DateUtil.now() + "\n");
        stringBuffer.append("触发原因:" + e.getMessage());
        log.error(stringBuffer.toString());
        //数据校验异常
        if (e instanceof BindException) {
            return AjaxResult.fail(((BindException) e).getBindingResult().getAllErrors().get(0).getDefaultMessage(), null);
        } else {
            return AjaxResult.error(HttpStatus.ERROR, e.getMessage());
        }
    }

}
